var IssueOutOrder = function () {
  var EleOrderSelect = function () {
    var template = /* html */ `
      <div v-if="electroplateList!==null">
        <filter-select class="issue-input" v-model="electroplateId" size="mini" :options="electroplateList" value-field="id" label-field="name"
          :filter-method="filterMethod" @change="handleChange">
        </filter-select>
      </div>
    `;

    return {
      props: {
        order: {
          type: Object,
          required: true
        },
        eleDataObj: {
          type: Object,
          required: true
        }
      },

      watch: {
        "order.outOrder.electroplate": function () {
          if (this.inputValue !== null) {
            this.inputValue = null;
            return;
          }

          var electroplate = this.order.outOrder.electroplate;
          this.electroplateId = electroplate === '' ? '' : electroplate.id;
        }
      },

      computed: {
        electroplate: function () {
          var electroplateId = this.electroplateId;
          if (electroplateId === '') {
            return '';
          }

          var electroplateList = this.electroplateList;
          var electroplate = _.find(electroplateList, {
            id: electroplateId
          });
          return electroplate;
        }
      },

      data: function () {
        var eleData = this.eleDataObj[this.order.orderId];
        var electroplate = this.order.outOrder.electroplate;
        return {
          eleData: eleData,
          electroplateList: null,
          electroplateId: electroplate === '' ? '' : electroplate.id,
          inputValue: null,
          canSelect: false
        };
      },

      created: function () {
        this.initData();
      },

      methods: {
        initData: function () {
          var order = this.order;
          if (order.canEle) {
            this.setElectroplateList();
            return;
          }
          var eleData = this.eleData;
          var material = eleData.material;
          var eleColorObj = eleData.eleColorObj;
          var electroplateType = material[order.materialType];
          var eleColor = eleColorObj[electroplateType];
          if (eleColor === undefined) {
            this.setElectroplateList();
            return;
          }

          this.electroplateList = eleColor;
        },

        setElectroplateList: function () {
          var eleColorObj = this.eleData.eleColorObj;
          var electroplateList = [];
          for (var key in eleColorObj) {
            electroplateList.pushArray(eleColorObj[key]);
          }
          this.electroplateList = electroplateList;
        },

        filterMethod: function (query, option) {
          var materialType = option.materialType;
          materialType = materialType.toLowerCase();
          if (materialType.indexOf(query) !== -1) {
            return true;
          }
          var color = option.color;
          color = color.toLowerCase();
          if (color.indexOf(query) !== -1) {
            return true;
          }
          return false;
        },

        handleChange: function () {
          this.inputValue = this.electroplateId;
          var electroplate = this.electroplate;
          this.order.outOrder.electroplate = electroplate;
          this.$emit('change', electroplate);
        }
      },

      components: {
        FilterSelect: FilterSelect
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="issue-out-order" v-loading.fullscreen.lock="loading">
      <div style="margin-bottom:10px;">
        <el-button size="medium" type="primary" @click="issueOrder">发料到外协</el-button>
      </div>
      <div class="issue-order-table-div">
        <el-table fit stripe border :data="orderList" style="width: 100%" height="parent">
          <el-table-column prop="companyOrderId" label="订单编号" min-width="130px" header-align="center">
          </el-table-column>
          <el-table-column prop="factoryNo" label="工厂型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="articleNo" label="客户型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="model" label="规格" min-width="110px" header-align="center">
          </el-table-column>
          <el-table-column column-key="supplier" label="外协供应商" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <el-select filterable class="issue-input" v-model="scope.row.outOrder.supplier" size="mini" value-key="id" @change="supplierChange(scope.row)"
                :disabled="scope.row.outOrder.technologyLoading">
                <el-option v-for="supplier in supplierList" :key="supplier.id" :value="supplier" :label="supplier.supplierName"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column column-key="technology" label="加工工艺" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <el-select filterable class="issue-input" v-model="scope.row.outOrder.technology" size="mini" value-key="id" @change="technologyChange(scope.row)"
                :loading="scope.row.outOrder.technologyLoading">
                <el-option v-for="prodCycle in scope.row.outOrder.prodCycleList" :key="prodCycle.id" :value="prodCycle" :label="prodCycle.technology"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column column-key="flowCycle" label="流程周期" min-width="110px" header-align="center">
            <template slot-scope="scope">
              <el-input-number class="issue-input" size="mini" v-model="scope.row.outOrder.flowCycle" :min="1" :controls="false" :precision="0"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column column-key="valuationUint" label="计价单位" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input class="issue-input" size="mini" v-model="scope.row.outOrder.valuationUint"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="materialType" label="加工对象" min-width="120px" align="center">
          </el-table-column>
          <el-table-column column-key="canEle" label="是否电镀" min-width="100px" align="center">
            <template slot-scope="scope">
              <el-select v-if="scope.row.outOrder.canEle" class="issue-input" size="mini" v-model="scope.row.outOrder.hasEle">
                <el-option :value="false" label="否"></el-option>
                <el-option :value="true" label="是"></el-option>
              </el-select>
              <span v-else>{{scope.row.outOrder.hasEle?'是':'否'}}</span>
            </template>
          </el-table-column>
          <el-table-column column-key="eleDataObj" label="电镀类型" min-width="160px" align="center">
            <template slot-scope="scope" v-if="scope.row.outOrder.hasEle">
              <ele-order-select :order="scope.row" :ele-data-obj="eleDataObj"></ele-order-select>
            </template>
          </el-table-column>
          <el-table-column prop="color" label="编号" min-width="100px" header-align="center">
          </el-table-column>
          <el-table-column prop="colorDescription" label="描述" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="selfOutFuCount" label="外协数量" min-width="100px" align="center">
          </el-table-column>
          <el-table-column column-key="valuationCount" label="计价数量" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero class="issue-input" size="mini" v-model="scope.row.outOrder.valuationCount" :min="1/Math.pow(10,scope.row.outOrder.valuationCountPrecision)"
                :max="100000000-1/Math.pow(10,scope.row.outOrder.valuationCountPrecision)" :controls="false" :precision="scope.row.outOrder.valuationCountPrecision"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column column-key="unitPrice" label="外协单价" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero class="issue-input" size="mini" v-model="scope.row.outOrder.unitPrice" :min="0" :max="99999999.99" :controls="false" :precision="2">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column column-key="remark" label="备注" min-width="190px" header-align="center">
            <template slot-scope="scope">
              <el-input class="issue-input" size="mini" v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  `;

  return {
    props: {
      materials: {
        type: Object,
        required: true
      },
      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    data: function () {
      return {
        loading: false,
        orderList: this.getOrderList(),
        eleDataObj: null,
        supplierList: []
      };
    },

    created: function () {
      this.initData();
    },

    methods: {
      getOrderList: function () {
        var materials = this.materials;
        var orderList = _.map(materials, function (material) {
          var obj = _.cloneDeep(material);
          var unit = material.unit;
          if (SysUtil.isEmpty(unit)) {
            unit = '付';
          }
          if (unit === '付') {
            obj.selfOutFuCount = obj.receiveCount;
          }
          var valuationCountPrecision = SysUtil.getMaterialNumberPrecision(unit, 2);
          obj.outOrder = {
            supplier: '',
            technologyLoading: false,
            prodCycleList: [],
            technology: '',
            flowCycle: undefined,
            unitPrice: undefined,
            valuationUint: unit,
            valuationCountPrecision: valuationCountPrecision,
            valuationCount: material.selfOutFuCount,
            electroplate: '',
            hasEle: false,
            canEle: false
          };
          return obj;
        });
        return orderList;
      },

      initData: function () {
        this.loading = true;
        var self = this;
        Promise.all([
          this.setSupplierList(),
          this.setEleData()
        ]).then(function () {
          var orderList = self.orderList;
          var eleDataObj = self.eleDataObj;
          for (var i = 0; i < orderList.length; i++) {
            var order = orderList[i];
            var eleOption = ModuleUtil.getEleOrderSelect(order, eleDataObj);
            order.outOrder.hasEle = eleOption.hasEle;
            order.outOrder.canEle = eleOption.canEle;
          }
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        })
      },

      setSupplierList: function () {
        var dropdownOption = this.dropdownOption;
        var supplierList = dropdownOption.supplierList;
        if (supplierList !== undefined) {
          this.supplierList = supplierList;
          return Promise.resolve(supplierList);
        }

        var self = this;
        return SysUtil.getSupplierDropDown().then(function (supplierList) {
          dropdownOption.supplierList = supplierList;
          self.supplierList = supplierList;
          return supplierList;
        });
      },

      setEleData: function () {
        var orderList = this.orderList;
        var orderIds = _.map(orderList, 'orderId');
        orderIds = _.uniq(orderIds);
        var promiseList = [];
        for (var i = 0; i < orderIds.length; i++) {
          var orderId = orderIds[i];
          promiseList.push(
            ModuleUtil.getEleOrderData(orderId).then(function (eleData) {
              var eleColorObj = eleData.eleColorObj;
              for (var key in eleColorObj) {
                var eleColorList = eleColorObj[key];
                for (var i = 0; i < eleColorList.length; i++) {
                  var obj = eleColorList[i];
                  obj.id = `${obj.materialType}-${obj.lineNo}`;
                  obj.name = `${obj.materialType}(${obj.color})`;
                }
              }
              return eleData;
            })
          );
        }

        var self = this;
        return Promise.all(promiseList).then(function (data) {
          var eleDataObj = {};
          for (var i = 0; i < data.length; i++) {
            eleDataObj[orderIds[i]] = data[i];
          }
          self.eleDataObj = eleDataObj;
          return eleDataObj;
        });
      },

      supplierChange: function (order) {
        var outOrder = order.outOrder;
        var supplier = outOrder.supplier;
        outOrder.technologyLoading = true;
        return ajaxRequest('putOutNew/getPutoutFlowCycle', {
          supplierId: supplier.supplierId,
          status: 1
        }).then(function (res) {
          var prodCycleList = res.returnData;
          outOrder.prodCycleList = prodCycleList;
          outOrder.technologyLoading = false;
          outOrder.technology = '';
          return prodCycleList;
        }).catch(function () {
          outOrder.technologyLoading = false;
          return [];
        });
      },

      technologyChange: function (order) {
        var outOrder = order.outOrder;
        var technology = outOrder.technology;
        var flowCycle = technology.flowCycle;
        if (SysUtil.isEmpty(flowCycle)) {
          flowCycle = undefined;
        }
        outOrder.flowCycle = flowCycle;

        var unitPrice = technology.unitPrice;
        if (SysUtil.isEmpty(unitPrice)) {
          unitPrice = undefined;
        }
        outOrder.unitPrice = unitPrice;
      },

      issueOrder: function () {
        var orderList = this.orderList;
        var fields = ['supplier', 'technology', 'flowCycle', 'valuationUint', 'valuationCount', 'unitPrice'];

        for (var i = 0; i < orderList.length; i++) {
          var order = orderList[i];
          var outOrder = order.outOrder;
          var code = CheckVaildUtil.checkNullField(fields, outOrder);
          if (code !== '') {
            var msg = i18n.getMsg(`createIssueNote.error.${code}`);
            this.$alert(msg, '信息');
            return;
          }

          if (outOrder.unitPrice === 0) {
            this.$alert('单价不能为0', '信息');
            return;
          }

          if (outOrder.hasEle) {
            if (outOrder.electroplate === '') {
              this.$alert('请选择电镀类型', '信息');
              return;
            }
          }
        }

        var metailArray = [];
        var putoutOrderArray = [];
        for (var i = 0; i < orderList.length; i++) {
          var order = orderList[i];
          var issuePostData = ModuleUtil.getIssuePostData(order, 'approvalOrder');
          metailArray.pushArray(issuePostData);

          var outOrderPostData = ModuleUtil.getIssueOutOrderPostData(order);
          putoutOrderArray.push(outOrderPostData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest('warehouse/savePutOutFromWarehouse', {
          metailArray: JSON.stringify(metailArray),
          putoutOrderArray: JSON.stringify(putoutOrderArray)
        }).then(function (msg) {
          self.$alert(msg, '信息', {
            callback: function () {
              self.$emit('issue-success');
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      EleOrderSelect: EleOrderSelect
    },

    template: template
  };
}();
